from http import HTTPStatus
import dashscope
import json

# pip install dashscope
# export DASHSCOPE_API_KEY=sk-178f7fc245424c92b4b93ebc4eac1df8

# dashscope.api_key = "your-dashscope-api-key"


def call_with_callback(messages):
    """
    请求语音解析 返回：

    """
    task_response = dashscope.audio.asr.Transcription.async_call(
        model="paraformer-mtl-v1",
        file_urls=messages,
    )

    transcribe_response = dashscope.audio.asr.Transcription.wait(
        task=task_response.output.task_id
    )
    if transcribe_response.status_code == HTTPStatus.OK:
        # print(json.dumps(transcribe_response.output, indent=4, ensure_ascii=False))
        # print("transcription done!")
        return json.dumps(transcribe_response.output, indent=4, ensure_ascii=False)
    else:
        return None


def call_with_messages(messages):
    """
        请求AI会话 返回：
    {'choices': [
        {
            'finish_reason': 'stop',
            'message': {
                'role': 'assistant',
                'content': '材料：...'
            }
        }]
    }
    """
    # messages = [
    #     {"role": "system", "content": "You are a helpful assistant."},
    #     {"role": "user", "content": "如何做西红柿炒鸡蛋？"},
    # ]
    response = dashscope.Generation.call(
        model="qwen-max",
        messages=messages,
        result_format="message",
    )
    if response.status_code == HTTPStatus.OK:
        # print(response)
        return response.output
    else:
        # print(
        #     "Request id: %s, Status code: %s, error code: %s, error message: %s"
        #     % (
        #         response.request_id,
        #         response.status_code,
        #         response.code,
        #         response.message,
        #     )
        # )
        return None
